package com.jack.leetcode.每日一题;

import java.util.HashMap;
import java.util.Map;

public class 最小覆盖子串 {

    public String minWindow(String s, String t) {
        Map<Character,Integer> map = new HashMap<>();
        int minLen = Integer.MAX_VALUE;
        int minStart = 0;
        int missType = 0;
        for(int i=0;i<t.length();i++){
            char c = t.charAt(i);
            if(map.containsKey(c)){
                map.put(c,map.get(c)+1);
            }else{
                missType++;
                map.put(c,1);
            }
        }
        int left = 0,right = 0;
        for(;right<s.length();right++){
            char rightChar = s.charAt(right);
            if(map.containsKey(rightChar)){
                map.put(rightChar,map.get(rightChar)-1);
            }
            if(map.containsKey(rightChar)&&map.get(rightChar)==0){
                missType--;
            }
            while(missType==0){
                if(right-left+1<minLen){
                    minLen = right-left+1;
                    minStart = left;
                }
                char leftChar = s.charAt(left);
                if(map.containsKey(leftChar)){
                    map.put(leftChar,map.get(leftChar)+1);
                }
                if(map.containsKey(leftChar)&&map.get(leftChar)>0){
                    missType++;
                }
                left++;
            }
        }
        if(minStart<s.length()&&minStart+minLen<=s.length()){
            return s.substring(minStart,minStart+minLen);
        }else{
            return "";
        }
    }
}
